package controller.dao;

import model.*;
import java.util.*;
import javax.persistence.*;

public class Dao_Category {
		EntityManager manager;
		
		public boolean save(Category category) {
			try	{
				manager = Factory.factory().createEntityManager();
				manager.getTransaction().begin();		
				manager.merge(category);
				manager.getTransaction().commit();
				manager.close();
				return true;
			}catch (Exception e) {
				return false;
			}
		}
		
		public List<Category> listAll(int inicio, int quant){
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();
			Query query = (Query) manager.createQuery("SELECT c FROM Category c where c.active = 1" );
			@SuppressWarnings("unchecked")
			List<Category> category =  query.setMaxResults(quant).setFirstResult(inicio).getResultList();
			manager.close();
			return category;
		}
		
		public List<Category> listAll(){
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();
			Query query = (Query) manager.createQuery("SELECT c FROM Category c where c.active = 1" );
			@SuppressWarnings("unchecked")
			List<Category> category =  query.getResultList();
			manager.close();
			return category;
		}
		
		public Long totalCategory(){
			manager = Factory.factory().createEntityManager();
			manager.getTransaction().begin();
			Query query = (Query) manager.createQuery("SELECT count(c) FROM Category c where c.active = 1" );
			
			Long total = (Long) query.getSingleResult();
			manager.close();
			return total;
		}
		
		public boolean update(Category category){
			try{
				manager = Factory.factory().createEntityManager();
				manager.getTransaction().begin();
				manager.merge(category);
				manager.getTransaction().commit();
				manager.close();
				return true;
			}catch (Exception e) {
				return false;
			}
		}
		
		public boolean delete(Category category){
			try {
				manager = Factory.factory().createEntityManager();
				manager.getTransaction().begin();
				manager.merge(category);
				manager.getTransaction().commit();
				manager.close();				
				return true;
			} catch (Exception e) {
				return false;
			}
		}
				
		public Category list(int id)	{
			try {
				manager = Factory.factory().createEntityManager();
				manager.getTransaction().begin();	
				Category category = manager.find(Category.class, id);
				manager.close();
				return category;
			} catch (Exception e) {
				return null;				
			}
		}
}
